// <copyright file="RoleService.cs" company="EnterpriseApi">
// Copyright (c) EnterpriseApi. All rights reserved.
// </copyright>

using EnterpriseApi.Models;
using EnterpriseApi.Repositories;

namespace EnterpriseApi.Services;

/// <summary>
/// 角色服务实现类，提供角色特有的业务逻辑操作
/// </summary>
public class RoleService : Service<Role>, IRoleService
{
    private readonly IRoleRepository _roleRepository;

    /// <summary>
    /// 初始化RoleService的新实例
    /// </summary>
    /// <param name="roleRepository">角色仓储</param>
    public RoleService(IRoleRepository roleRepository) : base(roleRepository)
    {
        _roleRepository = roleRepository;
    }

    /// <summary>
    /// 根据角色名称获取角色
    /// </summary>
    /// <param name="name">角色名称</param>
    /// <returns>角色对象，如果不存在则返回null</returns>
    public async Task<Role?> GetByNameAsync(string name)
    {
        return await _roleRepository.GetByNameAsync(name);
    }

    /// <summary>
    /// 检查角色名称是否已存在
    /// </summary>
    /// <param name="name">角色名称</param>
    /// <returns>角色名称是否已存在</returns>
    public async Task<bool> IsNameExistsAsync(string name)
    {
        if (string.IsNullOrWhiteSpace(name))
        {
            throw new ArgumentException("角色名称不能为空", nameof(name));
        }

        return await _roleRepository.IsNameExistsAsync(name);
    }

    /// <summary>
    /// 创建新角色
    /// </summary>
    /// <param name="role">角色信息</param>
    /// <returns>创建的角色</returns>
    public async Task<Role> CreateRoleAsync(Role role)
    {
        if (role == null)
        {
            throw new ArgumentNullException(nameof(role));
        }

        if (string.IsNullOrWhiteSpace(role.Name))
        {
            throw new ArgumentException("角色名称不能为空", nameof(role.Name));
        }

        // 检查角色名称是否已存在
        if (await _roleRepository.IsNameExistsAsync(role.Name))
        {
            throw new ArgumentException($"角色名称 '{role.Name}' 已存在", nameof(role.Name));
        }

        role.CreatedAt = DateTime.UtcNow;
        role.UpdatedAt = null;

        return await _roleRepository.AddAsync(role);
    }
}